package com.mysum.hessian;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.Date;
import java.util.concurrent.atomic.AtomicLong;

import com.caucho.hessian.io.Hessian2Input;
import com.caucho.hessian.io.Hessian2Output;

public class HessianSerializabler {
	public static void main(String[] args) {
		for (int i = 0; i < 2; i++) {
			UserInfo userInfo = new UserInfo(30, "dongh", new Date());
			byte[] serior = toBytes(userInfo);
			System.out.println(serior);
			UserInfo newUserInfo = (UserInfo) toObject(serior,UserInfo.class);
			System.out.println(newUserInfo);

			Integer n = 5;
			System.out.println(toBytes(n));
			System.out.println(toBytes("aaaa"));
			byte[] atom = toBytes(new AtomicLong(10));
			System.out.println(atom);
			System.out.println(toObject(atom, AtomicLong.class));
			
			Date now = new Date();
			byte[] nowa = toBytes(now);
			System.out.println(nowa);
			System.out.println(now);
			System.out.println(toObject(nowa, Date.class));
		}
	}

	public static byte[] toBytes(Object obj) {
		byte[] result = null;
		ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
		Hessian2Output objectOutputStream = new Hessian2Output(byteOutputStream);
		try {
			objectOutputStream.writeObject(obj);
			objectOutputStream.flush();
			result = byteOutputStream.toByteArray();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				objectOutputStream.close();
				byteOutputStream.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		return result;
	}

	public static <T> T toObject(byte[] bytes, Class<T> clazz) {
		T result = null;
		ByteArrayInputStream byteInputStream = new ByteArrayInputStream(bytes);
		Hessian2Input objectInputStream = new Hessian2Input(byteInputStream);
		try {
			result = (T) objectInputStream.readObject();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				objectInputStream.close();
				byteInputStream.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return result;
	}
}
